import SnakeCell from "./SnakeCell";
import DebugUtils from "./utils/DebugUtils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Snake extends cc.Component {

    @property(cc.SpriteFrame)
    head: cc.SpriteFrame = null

    @property(cc.SpriteFrame)
    body: cc.SpriteFrame = null

    private pool: SnakeCell[] = []

    static readonly TAG_HEAD: number = 1
    static readonly TAG_BODY: number = 2

    private targetPos: cc.Vec2 = cc.v2()
    private tempPos: cc.Vec2 = cc.v2()

    start() {
        this.reset()
    }

    reset() {

        if (this.node.childrenCount > 0) {
            this.node.children.forEach(item => {
                this.pool.push(item.getComponent(SnakeCell))
            })
            this.node.removeAllChildren(true)
        }
        this.node.setAnchorPoint(0.5, 0.5)
        this.node.width = this.node.height = 20
        DebugUtils.showBound(this.node)

        //加一个头.
        let head = this.pool.pop()
        if (!head) {
            head = SnakeCell.instance(this.head)
        } else {
            head.setSkin(this.head)
        }
        head.tag = Snake.TAG_HEAD

        this.node.addChild(head.node)

        for (let i = 0; i < 1; i++) {
            let body = this.pool.pop()
            if (!body) {
                body = SnakeCell.instance(this.body)
            } else {
                body.setSkin(this.body)
            }
            body.tag = Snake.TAG_BODY
            this.node.addChild(body.node)
        }
        this._layout()
    }

    private _layout() {
        let startY = 0
        this.node.children.forEach(item => {
            item.position = cc.v2(0, startY)
            startY -= item.height
        })
    }

    move(offset: cc.Vec2) {
        offset.y = 0
        this.targetPos.addSelf(offset)
        console.log("移动距离:", this.targetPos)
        this.loop()
    }

    private loop() {
        this.tempPos.set(this.targetPos)
        this.node.children.forEach(item => {
            this.tempPos.subSelf(item.position)
            if (this.tempPos.x == 0) return;
            // let angle = Math.atan2(this.tempPos.y, this.tempPos.x)
            // let deltaX = item.height * Math.cos(angle)
            // let deltaY = item.height * Math.sin(angle)
            // item.position = item.position.addSelf(cc.v2(deltaX, deltaY))
            console.log("pos:", this.tempPos)
            this.tempPos.set(item.position)
        })
    }

    update(dt) {

    }
}










